package com.seecen.webproject.service;

import com.seecen.webproject.dao.UserDao;
import com.seecen.webproject.entity.User;
import com.seecen.webproject.exception.PasswordNotMatchException;
import com.seecen.webproject.exception.UserNameNotFountException;
import com.seecen.webproject.vo.Result;

public class UserService {

    private UserDao userDao = new UserDao();

    public User login(User user) throws UserNameNotFountException, PasswordNotMatchException {
        User dbUser = userDao.queryByUsername(user.getUsername());
        if (dbUser == null) throw new UserNameNotFountException();
        if (!dbUser.getPassword().equals(user.getPassword())) throw new PasswordNotMatchException();
        return dbUser;
    }

    public Result<User> register(User user) {
        User dbUser = userDao.queryByUsername(user.getUsername());
        if (dbUser != null) return Result.fail(Result.FAIL_CODE, "要注册的用户名已经存在!");

        int res = userDao.save(user);

        if(res > 0) {
            dbUser = userDao.queryByUsername(user.getUsername());
            return Result.success(dbUser);
        }
        return Result.fail(Result.FAIL_CODE, "未知错误，请联系管理员!");
    }
}
